package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
    private static final String VALUE_PREFIX = UUID.randomUUID().toString(true) + "-";
    //初始化lua脚本
    private static DefaultRedisScript<Long> redisScript;
    static {
        redisScript = new DefaultRedisScript<Long>();
        redisScript.setLocation(new ClassPathResource("unlock.lua"));
        redisScript.setResultType(Long.class);
    }
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock() {
        //组装value uuid+线程id
        long id = Thread.currentThread().getId();
        String value = VALUE_PREFIX + id;
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, value, 120l, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    @Override
    public void unlock() {
        //使用lua脚本保证原子性
        stringRedisTemplate.execute(redisScript,
                Collections.singletonList(KEY_PREFIX + name),
                VALUE_PREFIX + Thread.currentThread().getId());

        //避免误删除，判断锁是否为同一把锁
        /*String value = VALUE_PREFIX + Thread.currentThread().getId();
        String redisValue= stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (value.equals(redisValue)){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }*/
    }
}
